﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Text;

namespace MicroDb
{
    public class MicroDbOptions
    {
        public MicroDbOptions()
        {
            DbConnectionBuilders = new Dictionary<string, (MicroDbType, string)>();
        }

        public MicroDbOptions AddConnection(string dbSource, string dbConnectionString, MicroDbType microDbType = MicroDbType.MySql)
        {
            if (!DbConnectionBuilders.ContainsKey(dbSource))
                DbConnectionBuilders.Add(dbSource, (microDbType, dbConnectionString));
            return this;
        }


        public IDictionary<string, (MicroDbType, string)> DbConnectionBuilders { get; }
    }

    class MicroDbConfigure : IConfigureOptions<MicroDbOptions>
    {
        private readonly IConfiguration configuration;

        public MicroDbConfigure(IConfiguration configuration)
        {
            this.configuration = configuration;
        }
        public void Configure(MicroDbOptions options)
        {
            foreach (var item in configuration.GetSection("connectionStrings").GetChildren())
            {
                options.AddConnection(item.Key, item.Value);
            }
            ChangeToken.OnChange(configuration.GetReloadToken, () =>
            {
                foreach (var item in configuration.GetSection("connectionStrings").GetChildren())
                {
                    options.AddConnection(item.Key, item.Value);
                }
            });
        }
    }

}
